<?php
namespace system\platform\controller;

class Index{

	//登录
	public function index(){
	   
		//判断是否登录---登录跳转到管理首页
		if(!empty($_SESSION['platform']['admin']['admin_id'])){
			header('Location:'.url([ 'platform' ,'platform','index']));
			exit();
		}

		require view('default/index/login.tpl.php');

	} 


	//登录查验
	public function api_login_check(){

		if( isset($_POST['username']) && $_POST['username']!='' 
			&& isset($_POST['password']) && $_POST['password']!='' 
			&& isset($_POST['code'])   ){


			if( isset( $GLOBALS['config']['应用入口']['login_captcha'] ) && $GLOBALS['config']['应用入口']['login_captcha']==='启用' ){
				$code = strtolower( trim( $_POST['code'] ) );
				if( $code!='' && $code != strtolower($_SESSION['platform']['captcha_code']) ){
					$arr['code']=400;
					$arr['message']='验证码错误!' ;
					$arr['data']='';
					exit(json_encode($arr));
				}

			}

			// 用户查询
			$login_account = trim( $_POST['username'] ) ;
			$password = substr(md5( trim($_POST["password"]) ),15,25);
			$sql="select * from " . tablename('sys_admin') . " where is_delete=0 and status=1 and login_account = '$login_account' and login_password = '$password' ";
			$ret = $GLOBALS["db"]->query($sql)->fetch();
			if(!empty($ret)){
				$data = ['last_login_ip'=>get_ip() , 'last_login_time'=>time(),'login_count'=>1+$ret['login_count'] ];
				pdo_update( 'sys_admin' , $data , ['admin_id'=>$ret['admin_id'] ] );

				$_SESSION['platform']['admin']['admin_id'] = $ret['admin_id'];
				$_SESSION['platform']['admin']['name'] = $ret['name'];
				$_SESSION['platform']['admin']['login_account'] = $ret['login_account'];
				unset($_SESSION['platform']['captcha_code']);
				
				$url = '';
				if( isset($GLOBALS['config']['应用入口']['platform']) && $GLOBALS['config']['应用入口']['platform']!=''){
					$url = url( [ $GLOBALS['config']['应用入口']['platform'] ,'admin.index','index']);	//应用模块入口
				}else{
					$url = url('platform/platform/index');	//控制台
				} 
				$arr['code']=200;
				$arr['message']='登录成功!';
				$arr['data']=['url' => $url ];
			}else{
				$arr['code']=400;
				$arr['message']='账号或密码错误!';
				$arr['data']='';
			}
			
		}else{
			$arr['code']=400;
			$arr['message']='账号或密码为空!';
			$arr['data']='';
		}
		exit(json_encode($arr));
	} 

	//退出
	function logout(){
		$_SESSION['platform']['admin'] = null ;
		unset($_SESSION['platform']['admin']);
		message('退出登录！',url(['platform','index','index']));
	} 

	// 验证码
	// http://localhost/deep_phpwork/index.php?app=platform&c=index&a=captcha
	public function captcha(){
		// 验证码
		require _APP_PATH_ . "/library/deep/captcha/captcha.class.php";

		$captcha = new \library\deep\Captcha();

		$captcha->width  = 200;	//
		$captcha->height = 80;	//
		//$captcha->debug=true;
		$captcha->randomLength=4;

		$captcha->createImage();

		$_SESSION['platform']['captcha_code'] = $captcha->code;
		
	}



}